﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.Linq.SqlClient;

public partial class User_TransferMoney : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser();
        var profiles = from profile in db.UserProfiles where profile.userId == (Guid)user.ProviderUserKey select profile;
        if (Session["bankAccountId"] != null)
        {
            BankAccountCompany fromBankAccountCompany = getFromBankAccountCompany();
            if (profiles.First().CompanyId == fromBankAccountCompany.Company.CompanyId)
            {
                FromAccountLabel.Text = "Со счёта (" + fromBankAccountCompany.BankAccount.Amount.ToString() + " " + fromBankAccountCompany.BankAccount.Currency.Name + ") ";
                TransferButton.Enabled = true;
                FromAccountNumber.Text = Session["bankAccountId"].ToString();
            }
        }
    }

    protected BankAccountCompany getFromBankAccountCompany()
    {
        string bankAccountId = null;
        if (Session["bankAccountId"] != null)
        {
            bankAccountId = Session["bankAccountId"].ToString();
        }
        if (bankAccountId != null)
        {
            var bankAccounts = from bankAccount in db.BankAccountCompanies where bankAccount.BankAccountId == Convert.ToInt32(bankAccountId) select bankAccount;
            return bankAccounts.First();
        }
        return null;
    }


    protected void TransferButton_Click(object sender, EventArgs e)
    {
        BankAccountCompany fromBankAccountCompany = getFromBankAccountCompany();
        decimal transferAmount = Convert.ToDecimal(Amount.Text);
        switch (BankList.SelectedValue)
        {
            case "0":                
                var bankAccounts = from bankAccount in db.BankAccounts where bankAccount.BankAccountId == Convert.ToInt32(ToAccountNumber.Text) select bankAccount;
                if (bankAccounts.Count() != 0)
                {
                    if (bankAccounts.First().CurrencyId == fromBankAccountCompany.BankAccount.CurrencyId)
                    {
                        if (fromBankAccountCompany.BankAccount.Amount > transferAmount)
                        {
                            fromBankAccountCompany.BankAccount.Amount -= transferAmount;
                            bankAccounts.First().Amount += transferAmount;
                            db.SubmitChanges();
                        }
                        else
                        {
                            ErrorLabel.Text = "Недостаточно средств на счету.";
                            return;
                        }
                    }
                    else
                    {
                        double ToAccountCurrencyUSDRate = bankAccounts.First().Currency.USDExchangeRate;
                        decimal amountInToAccountCurrency = transferAmount / (decimal)(fromBankAccountCompany.BankAccount.Currency.USDExchangeRate / ToAccountCurrencyUSDRate);
                        if (fromBankAccountCompany.BankAccount.Amount > transferAmount)
                        {
                            var bankAccountsBank = from bankAccount in db.BankAccountBanks where bankAccount.BankAccount.CurrencyId == bankAccounts.First().CurrencyId select bankAccount;
                            var bankAccountsBank2 = from bankAccount in db.BankAccountBanks where bankAccount.BankAccount.CurrencyId == fromBankAccountCompany.BankAccount.CurrencyId select bankAccount;
                            if (bankAccountsBank.Count() != 0 && bankAccountsBank2.Count() != 0)
                            {
                                if (bankAccountsBank.First().BankAccount.Amount > transferAmount)
                                {
                                    fromBankAccountCompany.BankAccount.Amount -= transferAmount;
                                    bankAccountsBank2.First().BankAccount.Amount += transferAmount;
                                    bankAccountsBank.First().BankAccount.Amount -= amountInToAccountCurrency;
                                    bankAccounts.First().Amount += amountInToAccountCurrency;
                                    db.SubmitChanges();
                                }
                                else
                                {
                                    ErrorLabel.Text = "У банка недостаточно средств для конверсии.";
                                    return;
                                }
                            }
                            else
                            {
                                ErrorLabel.Text = "У банка недостаточно средств для конверсии.";
                                return;
                            }
                        }
                        else
                        {
                            ErrorLabel.Text = "Недостаточно средств на счету.";
                            return;
                        }
                    }
                }
                else
                {
                    ErrorLabel.Text = "Такой счёт не существует.";
                    return;
                }
                break;
            case "1":
                fromBankAccountCompany.BankAccount.Amount -= transferAmount;
                db.SubmitChanges();
                break;
        }
        Session.Remove("bankAccountId");
        Response.Redirect("~/User/Accounts.aspx");
    }
}